1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| #include <cstdio> #include <vector> #include <algorithm> using namespace std; const int maxn = 2e5 + 5; const int INF = 0x3f3f3f3f; struct E{ int to, nxt, l; }e[maxn << 1]; int head[maxn], tot = 0; void addedge(int u, int v, int l){ e[++tot].to = v, e[tot].nxt = head[u], e[tot].l = l; head[u] = tot; } bool vis[maxn]; int sz[maxn], Max[maxn], rt; void getRt(int cur, int fa, int totsz){ sz[cur] = 1; Max[cur] = -1; for (int i = head[cur]; i; i = e[i].nxt){ int v = e[i].to; if (v == fa || vis[v]) continue; getRt(v, cur, totsz); sz[cur] += sz[v]; Max[cur] = max(Max[cur], sz[v]); } Max[cur] = max(Max[cur], totsz - sz[cur]); if (Max[cur] < Max[rt]) rt = cur; } struct A{ int dis, dep, c; bool operator<(A x)const{ return dis < x.dis; } }; vector <A> v; int dis[maxn], dep[maxn]; void getDis(int cur, int fa, int c){ v.push_back((A){dis[cur], dep[cur], c}); for (int i = head[cur]; i; i = e[i].nxt){ int v = e[i].to; if (v == fa || vis[v]) continue; dep[v] = dep[cur] + 1; dis[v] = dis[cur] + e[i].l; getDis(v, cur, c); } } int n, K, ans = INF; void calc(int cur){ int cntC = 0; v.clear(); v.push_back((A){0, 0, 0}); for (int i = head[cur]; i; i = e[i].nxt){ int v = e[i].to; if (vis[v]) continue; dep[v] = 1; dis[v] = e[i].l; getDis(v, cur, ++cntC); }
sort(v.begin(), v.end()); vector <A>::iterator l = v.begin(), r = v.end() - 1; while (l < r){ if (l->dis + r->dis < K) ++l; else if (l->dis + r->dis > K) --r; else{ if (l->c != r->c) ans = min(ans, l->dep + r->dep); vector <A>::iterator t = l + 1; while (t->dis == l->dis){ if (t->c != r->c) ans = min(ans, t->dep + r->dep); ++t; } t = r - 1; while (t->dis == r->dis){ if (t->c != l->c) ans = min(ans, t->dep + l->dep); --t; } ++l, --r; } } } void dfs(int cur, int totsz){ vis[cur] = 1; calc(cur); for (int i = head[cur]; i; i = e[i].nxt){ int v = e[i].to; if (vis[v]) continue; rt = 0; int ssz = sz[v] > sz[cur] ? totsz - sz[cur] : sz[v]; getRt(v, cur, ssz); dfs(rt, ssz); } } int main(){
scanf("%d%d", &n, &K); for (int u, v, l, i = 1; i < n; i++){ scanf("%d%d%d", &u, &v, &l); ++u, ++v; addedge(u, v, l); addedge(v, u, l); } rt = 0; Max[0] = INF; getRt(1, 0, n); dfs(rt, n); if (ans != INF) printf("%d\n", ans); else puts("-1"); return 0; }
|